<template>
  <div class="patrolPoint h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code">{{ `巡视点 ${formData.code || ""}` }}</span>
      </template>
      <div class="plan-title">
        <div>
          <div v-show="!showInput" class="name">
            <span style="color: red"></span>
            <span>{{ titleName }}</span>
            <el-link
              v-show="titleEdit"
              style="font-size: 20px"
              icon="el-icon-edit-outline"
              @click="editTitle"
            ></el-link>
          </div>
          <div v-show="showInput" class="name-input">
            <el-input
              type="text"
              v-model="titleName"
              maxlength="64"
              show-word-limit
              @blur="loseFocus"
              @change="userInputTitle"
              placeholder="请输入名称"
              clearable
              ref="mark"
              ><template slot="prepend"
                >标题</template
              ></el-input
            >
          </div>
        </div>
        <el-button
          class="el-button--plain"
          size="mini"
          icon="el-icon-s-grid"
          @click="(event) => viewQrCode(event, true)"
          v-loading.fullscreen.lock="fullscreenLoading"
          v-if="pageType != 'add'"
          >查看二维码</el-button
        >
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <editForm
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="formData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <span class="titleLine"></span>
            巡视内容
          </template>
          <patrolContent
            :patrolEnvList="patrolEnvList"
            :patrolEquipList="patrolEquipList"
            :unEdit="unEdit"
            :type="patrolType"
            ref="patrolContent"
          />
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <div class="codeDiv topDistance" v-if="showQrCode">
      <div class="codeTop">
        <span class="codeTitle">二维码</span>
        <span class="codeClose" @click="() => (showQrCode = false)">
          <i class="el-icon-close"></i>
        </span>
      </div>
      <div class="codeContent" ref="codeImg">
        <!-- <el-image
          class="codeImg"
          style="width: 200px; height: 200px"
          :src="qrCodeUrl"
          fit="scale-down"
        >
          <div slot="error" class="image-slot errText">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image> -->
        <canvas
          id="canvas"
          width="280"
          height="420"
        ></canvas>
        <div class="QRCode" style="display: none" ref="qrCodeUrl"></div>
      </div>
      <div class="codeBtn">
        <el-button
          slot="reference"
          icon="el-icon-printer"
          class="el-button--plain"
          size="mini"
          @click="printCode"
          >打印</el-button
        >
        <el-button
          class="el-button--plain"
          size="mini"
          icon="el-icon-download"
          @click="downloadQrCode"
          >下载</el-button
        >
      </div>
    </div>
    <div
        ref="canvasImg"
        style="
          width: 280px;
          height: 420px;
          position: absolute;
          z-index: -999;
          left: 25%;
          top: 10%;
        "
      >
        <el-image
          style="
            width: 280px;
            height: 420px;
            border-radius: 10px;
            border: 1px solid rgb(116, 116, 116);
          "
          :src="canvasUrl"
          fit="scale-down"
        >
        </el-image>
      </div>
  </div>
</template>
<script>
import {
  queryPatrolPointDetail,
  addOrUpdatePatrolPoint,
  deletePatrolPoint,
} from "@/api/productionPlan/patrolPlan.js";
import patrolContent from "./patrolContent.vue";
import QRCode from "qrcodejs2";
export default {
  components: {
    patrolContent,
  },
  data() {
    return {
      activeNames: ["1", "2"],
      fullscreenLoading: false,
      backgroundImgUrl: require("@/assets/img/logo_blue.png"),
      showQrCode: false,
      userInput: false,
      canvasUrl:null,
      qrCodeUrl:null,
      titleName: "",
      showInput: false,
      hideBtn: false,
      titleEdit: true,
      patrolType: "equipment_room",
      creatInfo: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      basicConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "所属单位",
            prop: "pointDeptName",
            propArr: "pointDeptArr",
            idsStr: "pointDeptId",
            type: "dept-select",
            trigger: "change",
            multiple: false, //是否多选
            allowCreate: false,
            option: [],
            span: 8,
            required: true,
            disabled: false,
            methods: (val) => {
              this.changeType = val.value;
            },
          },
          {
            label: "巡视位置",
            prop: "locationName",
            propArr: "locationArr",
            idsStr: "locationId",
            type: "location-select",
            option: [],
            multiple: false,
            allowCreate: false,
            required: true,
            disabled: false,
            span: 8,
            methods: (val) => {
              this.producedTitle();
            },
          },
          {
            label: "巡视点类型",
            prop: "patrolPointType",
            type: "select",
            required: true,
            disabled: false,
            selectOption: this.$store.getters.dirtData("patrol_point_type"),
            span: 8,
            methods: (val) => {
              this.patrolType = val.value;
            },
          },
          {
            label: "RFID编号",
            prop: "rfidCode",
            type: "text",
            disabled: false,
            span: 8,
          },
        ],
      },
      formData: {},
      patrolEnvList: [],
      patrolEquipList: [],
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) ||
            this.formData.editable == 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["details", "add"].includes(this.pageType) ||
            this.formData.editable == 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    unEdit() {
      return (
        ["query", "detail"].includes(this.pageType) ||
        this.formData.editable == 0
      );
    },
  },
  created() {
    this.init();
  },
  mounted() {
    if (this.pageType == "add") {
      let deptOption = [
        {
          label: this.formData.pointDeptName,
          value: this.formData.pointDeptId,
          id: this.formData.pointDeptId,
        },
      ];
      setTimeout(() => {
        this.$refs.basicForm.setItemOption("pointDeptName", deptOption);
        this.$refs.basicForm.setFormItem(
          "pointDeptArr",
          this.formData.pointDeptId
        );
      }, 0);
    }
  },
  methods: {
    init() {
      let { id } = this.$route.query;
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          this.titleEdit = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
        this.$set(
          this.formData,
          "pointDeptId",
          this.$store.getters.currentOrgInfo.id
        );
        this.$set(
          this.formData,
          "pointDeptName",
          this.$store.getters.currentOrgInfo.name
        );
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    //手动输入标题
    userInputTitle(val) {
      if (val != "") {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    //初始化标题生成方式
    initTitleInput(formData) {
      let title = formData.locationName;
      if (formData.name != title) {
        this.userInput = true;
      }
    },
    //生成标题
    producedTitle() {
      let formData = this.$refs.basicForm.getCurrentData();
      let title = formData.locationName;
      if (!this.userInput) {
        this.titleName = title;
      }
    },
    //查看二维码
    async viewQrCode(event, type) {
      this.showQrCode = true;
      this.$nextTick(() => {
        new QRCode(this.$refs.qrCodeUrl, {
          text: this.formData.id, // 需要转换为二维码的内容
          width: 250,
          height: 250,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.L,
        });
      });
      setTimeout(() => {
        let el = document.querySelectorAll(".QRCode img");
        this.qrCodeUrl = el[0].src;
        this.loadQrCode();
      }, 100);
    },
    loadQrCode(type = "show") {
      let pointName = this.formData.name;
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      // let imgLog = new Image();
      let imgCode = new Image();
      // imgLog.src = this.backgroundImgUrl;
      imgCode.src = this.qrCodeUrl;
      ctx.fillStyle = "rgb(40, 26, 113)";
      ctx.fillRect(0, 340, 280, 80);
      ctx.textAlign = "center";
      ctx.strokeStyle = "white";
      ctx.font = "normal normal 200 14px Microsoft YaHei";
      let strlength1 = ctx.measureText(pointName).width;
      ctx.font = "normal normal 200 16px Microsoft YaHei";
      let strlength2 = ctx.measureText(pointName).width;
      ctx.font = "normal normal 200 24px Microsoft YaHei";
      let strlength3 = ctx.measureText(pointName).width;
      if (strlength1 > 520) {
        ctx.font = "normal normal 200 14px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 140, 365, 20, canvas);
      } else if (strlength2 > 520 && strlength1 < 520) {
        ctx.font = "normal normal 200 14px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 140, 375, 20, canvas);
      } else if (strlength2 > 260) {
        ctx.font = "normal normal 200 16px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 140, 375, 20, canvas);
      } else if (strlength3 > 260 && strlength2 < 260) {
        ctx.font = "normal normal 200 16px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 140, 385, 20, canvas);
      } else {
        ctx.font = "normal normal 200 24px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 140, 385, 20, canvas);
      }
      let imageData = ctx.getImageData(0, 0, 280, 420);
      for (let i = 0; i < imageData.data.length; i += 4) {
        // 当该像素是透明的,则设置成白色
        if (imageData.data[i + 3] == 0) {
          imageData.data[i] = 255;
          imageData.data[i + 1] = 255;
          imageData.data[i + 2] = 255;
          imageData.data[i + 3] = 255;
        }
      }
      ctx.putImageData(imageData, 0, 0);
      let url = canvas.toDataURL("image/jpg");
      this.canvasUrl = url;
      // imgLog.onload = () => {
      //   ctx.drawImage(imgLog, 20, 10, 200, 50);
      //   let url = canvas.toDataURL("image/jpg");
      //   this.canvasUrl = url;
      // };
      imgCode.onload = () => {
        // 此处二维码渲染位置上移
        ctx.drawImage(imgCode, 20, 50, 240, 240);
        // ctx.drawImage(imgCode, 20, 80, 240, 240);
        let url = canvas.toDataURL("image/jpg");
        this.canvasUrl = url;
      };
    },
    downloadQrCode(type = "show") {
      let pointName = this.formData.name;
      const canvas = document.createElement("canvas");
      canvas.width = "560";
      canvas.height = "840";
      const ctx = canvas.getContext("2d");
      ctx.fillStyle = "rgb(40, 26, 113)";
      ctx.fillRect(0, 680, 560, 160);
      ctx.textAlign = "center";
      ctx.strokeStyle = "white";
      ctx.font = "normal normal 200 28px Microsoft YaHei";
      let strlength1 = ctx.measureText(pointName).width;
      ctx.font = "normal normal 200 32px Microsoft YaHei";
      let strlength2 = ctx.measureText(pointName).width;
      ctx.font = "normal normal 200 40px Microsoft YaHei";
      let strlength3 = ctx.measureText(pointName).width;
      if (strlength1 > 1080) {
        ctx.font = "normal normal 200 28px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 280, 730, 40, canvas);
      } else if (strlength2 > 1080 && strlength1 < 1080) {
        ctx.font = "normal normal 200 28px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 280, 750, 40, canvas);
      } else if (strlength2 > 520) {
        ctx.font = "normal normal 200 32px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 280, 750, 40, canvas);
      } else if (strlength3 > 520 && strlength2 < 520) {
        ctx.font = "normal normal 200 32px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 280, 770, 40, canvas);
      } else {
        ctx.font = "normal normal 200 40px Microsoft YaHei";
        this.canvasTextAutoLine(pointName, ctx, 280, 770, 40, canvas);
      }
      let imageData = ctx.getImageData(0, 0, 560, 840);
      for (let i = 0; i < imageData.data.length; i += 4) {
        // 当该像素是透明的,则设置成白色
        if (imageData.data[i + 3] == 0) {
          imageData.data[i] = 255;
          imageData.data[i + 1] = 255;
          imageData.data[i + 2] = 255;
          imageData.data[i + 3] = 255;
        }
      }
      ctx.putImageData(imageData, 0, 0);
      let p1 = new Promise((resolve, reject) => {
        let imgLog = new Image();
        imgLog.src = this.backgroundImgUrl;
        imgLog.onload = () => {
          ctx.drawImage(imgLog, 40, 20, 400, 100);
          resolve(true);
        };
      });
      let p2 = new Promise((resolve, reject) => {
        let imgCode = new Image();
        imgCode.src = this.qrCodeUrl;
        imgCode.onload = () => {
          ctx.drawImage(imgCode, 40, 160, 480, 480);
          resolve(true);
        };
      });
      Promise.all([p1, p2])
        .then((res) => {
          let url = canvas.toDataURL("image/jpg");
          this.canvasUrl = url;
          let a = document.createElement("a");
          let event = new MouseEvent("click");
          a.download = pointName + "-二维码.png";
          a.href = url;
          a.dispatchEvent(event);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    /*
     str:要绘制的字符串
     ctx:canvas对象
     initX:绘制字符串起始x坐标
     initY:绘制字符串起始y坐标
     lineHeight:字行高，自己定义个值即可
*/
    canvasTextAutoLine(str, ctx, initX, initY, lineHeight, c) {
      let lineWidth = 0;
      let canvasWidth = c.width - 20;
      let lastSubStrIndex = 0;
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          //减去initX,防止边界出现的问题
          ctx.strokeText(
            str.substring(lastSubStrIndex, i),
            initX,
            initY,
            canvasWidth
          );
          initY += lineHeight;
          lineWidth = 0;
          lastSubStrIndex = i;
        }
        if (i == str.length - 1) {
          ctx.strokeText(
            str.substring(lastSubStrIndex, i + 1),
            initX,
            initY,
            canvasWidth
          );
        }
      }
    },
    printCode() {
      // this.$print.
      this.$print(this.$refs.canvasImg);
    },
    //获取标准详情
    getDetails(id) {
      queryPatrolPointDetail({ pointId: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.creatInfo = res.data;
          this.titleName = this.formData.name;
          this.patrolType = res.data.patrolPointType;
          this.patrolEnvList = JSON.parse(JSON.stringify(res.data.envs));
          this.patrolEquipList = JSON.parse(JSON.stringify(res.data.equips));
          if (this.formData.editable == 0) {
            this.basicConfig.itemArr.map((i) => (i.disabled = true));
            this.titleEdit = false;
          }
          let deptOption = [
            {
              label: this.formData.pointDeptName,
              value: this.formData.pointDeptId,
              id: this.formData.pointDeptId,
            },
          ];
          let addressOption = [
            {
              label: this.formData.locationName,
              value: this.formData.locationId,
              id: this.formData.locationId,
            },
          ];
          // this.$refs.basicForm.setItemOption(
          //   "equipmentName",
          //   equipmentOption
          // );
          setTimeout(() => {
            this.$refs.basicForm.setItemOption("pointDeptName", deptOption);
            this.$refs.basicForm.setItemOption("locationName", addressOption);
            this.$refs.basicForm.setFormItem(
              "pointDeptArr",
              this.formData.pointDeptId
            );
            this.$refs.basicForm.setFormItem(
              "locationArr",
              this.formData.locationId
            );
            // this.$refs.basicForm.setFormItem("equipmentArr", equipmentArr);
          }, 100);
        }
      });
    },
    //删除
    deleteId() {
      this.$confirm("确定要删除该巡视点吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePatrolPoint({ pointId: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.$utils.addOperateLog(this.formData.id, `删除了巡视点`);
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    async save() {
      try {
        let formData = await this.$refs.basicForm.getFormData();
        let patrolContent = this.$refs.patrolContent.getPatrolContent();
        if (this.titleName == "") {
          this.loseFocus();
        } else if (patrolContent.patrolEquipList.length == 0) {
          this.$message.warning("巡视设备不能为空");
        } else {
          formData.name = this.titleName;
          formData.envs = patrolContent.patrolEnvList;
          formData.equips = patrolContent.patrolEquipList;
          let res = await addOrUpdatePatrolPoint(formData);
          this.$message.success("保存成功");
          if (this.pageType == "add") {
            this.$utils.addOperateLog(res.data.id, `新建了巡视点`);
            this.updateListData();
            let obj = {
              id: res.data.id,
              pageType: "edit",
            };
            this.$router.push({
              query: obj,
            });
          } else {
            this.$utils.addOperateLog(this.formData.id, `修改了巡视点`);
            this.getDetails(this.formData.id);
            this.updateListData();
          }
        }
      } catch (error) {}
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.patrolPoint {
  // overflow: hidden;
  position: relative;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    display: flex;
    justify-content: space-between;

    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
.codeContent {
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
.codeDiv {
  position: absolute;
  width: 300px;
  height: 510px;
  background-color: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 4px;
  top: 120px;
  right: 10px;
  z-index: 999;
  .codeTop {
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
    .codeClose {
      padding: 5px 15px;
      cursor: pointer;
    }
  }
  .codeTitle {
    text-align: left;
    padding: 5px 15px;
  }
  .codeBtn {
    padding: 15px;
  }
}
.topDistance {
  top: 170px;
}
#canvas {
  border: 1px solid rgb(116, 116, 116);
  border-radius: 10px;
  letter-spacing: 2px;
  background-color: #fff;
}
</style>